package com.presto.directo.utils

import android.content.Context
import java.lang.Exception

object SPUtil {

    lateinit var context: Context
    const val path = "xml"

    @JvmOverloads
    fun put(key: String, value: Any?, xml: String = path) {
        context.getSharedPreferences(xml, Context.MODE_PRIVATE).edit().apply {
            var v = value
            if (null == v) v = ""
            if (v is String) {
                putString(key, v)
            } else if (v is Int) {
                putInt(key, v)
            } else if (v is Boolean) {
                putBoolean(key, v)
            } else if (v is Float) {
                putFloat(key, v)
            } else if (v is Long) {
                putLong(key, v)
            }
            apply()
        }

    }

    @JvmOverloads
    fun putObject(key: String, value: Any?, xml: String = path) {
        val json = try {
            value?.toJson() ?: ""
        } catch (e: Exception) {
            ""
        }
        put(key, json, xml)
    }

    inline fun <reified T> getObject(key: String, xml: String = path): T? {
        val json = get<String>(key, "", xml)
        if (json.isBlank()) {
            return null
        }
        return try {
            GsonUtil.getInstance().fromJson(json, T::class.java)
        } catch (e: Exception) {
            null
        }
    }

    @JvmOverloads
    fun <T> get(key: String, defaultValue: Any, xml: String = path): T {
        context.getSharedPreferences(xml, Context.MODE_PRIVATE).apply {
            if (defaultValue is Int) {
                return getInt(key, defaultValue) as T
            } else if (defaultValue is Boolean) {
                return getBoolean(key, defaultValue) as T
            } else if (defaultValue is Float) {
                return getFloat(key, defaultValue) as T
            } else if (defaultValue is Long) {
                return getLong(key, defaultValue) as T
            }
            return getString(key, defaultValue as String) as T
        }

    }

    @JvmOverloads
    fun clear(xml: String = path) {
        context.getSharedPreferences(xml, Context.MODE_PRIVATE).edit().apply {
            clear().apply()
        }
    }
}